package org.jeecg.modules.fund.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bank.entity.YcUserhomeBank;
import org.jeecg.modules.bank.entity.YcYingshengBank;
import org.jeecg.modules.bank.mapper.YcUserhomeBankMapper;
import org.jeecg.modules.bank.service.IYcYingshengBankService;
import org.jeecg.modules.front.entity.vo.WithdrawFund;
import org.jeecg.modules.front.entity.vo.WithdrawOrder;
import org.jeecg.modules.front.util.FundDate;
import org.jeecg.modules.front.util.YinShengUtil;
import org.jeecg.modules.fund.entity.*;
import org.jeecg.modules.fund.mapper.*;
import org.jeecg.modules.fund.service.*;
import org.jeecg.modules.gongqiang.entity.MallConfiguration;
import org.jeecg.modules.gongqiang.entity.Userhome;
import org.jeecg.modules.gongqiang.entity.YcYingshengUserwallt;
import org.jeecg.modules.gongqiang.mapper.MallConfigurationMapper;
import org.jeecg.modules.gongqiang.mapper.UserhomeMapper;
import org.jeecg.modules.gongqiang.service.IMallConfigurationService;
import org.jeecg.modules.gongqiang.service.IYcYingshengUserwalltService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description: 基金订单表
 * @Author: jeecg-boot
 * @Date:   2024-08-29
 * @Version: V1.0
 */
@Service
public class UserhomeOrderServiceImpl extends ServiceImpl<UserhomeOrderMapper, UserhomeOrder> implements IUserhomeOrderService {
    @Autowired
    private IYcYingshengTransferService ycYingshengTransferService;

    @Autowired
    private IYcYingshengUserwalltService ycYingshengUserwalltService;



    @Autowired
    private IYcYingshengTransferLogService ycYingshengTransferLogService;


    @Autowired
    private IYcYingshengBankService ycYingshengBankService;

    @Resource
    private UserhomeFundMapper userhomeFundMapper;

    @Resource
    private UserhomeMapper userhomeMapper;

    @Resource
    private FundMapper fundMapper;
    @Resource
    private YcUserhomeBankMapper ycUserhomeBankMapper;
    @Resource
    private UserhomeWalletLogMapper userhomeWalletLogMapper;

    @Resource
    private UserhomeWalletFundLogMapper userhomeWalletFundLogMapper;


    @Resource
    private org.jeecg.modules.gongqiang.mapper.MallConfigurationMapper mallConfigurationMapper;


    private final ReentrantLock lock = new ReentrantLock();





    @Override
    public IPage<UserhomeOrder> pageList(Page<UserhomeOrder> page, QueryWrapper<UserhomeOrder> queryWrapper) {
        return this.baseMapper.getPageList(page, queryWrapper);
    }

    @Override
    public UserhomeOrder getByIdLock(String orderId) {
        return this.baseMapper.getByIdLock(orderId);
    }



    @Override
    public void operateStatus(String orderId,Integer status) {
        this.baseMapper.operateStatus(orderId, status);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<JSONObject> callBack(String outTradeNo, String totalAmount,String tradeSn) {
        UserhomeOrder userhomeOrder = this.baseMapper.getByOrderNum(outTradeNo);
        if(oConvertUtils.isEmpty(userhomeOrder))
        {
            return Result.error("订单不存在");
        }
       /* String tprice = String.format("%.2f", userhomeOrder.getAmount());
        if (!tprice.equals(totalAmount)) {
            return Result.error("金额错误");
        }*/
        //待支付变成已支付
        if(userhomeOrder.getStatus()==0)
        {
            userhomeOrder.setStatus(1);
            //用户基金列表新增目前购买一次新增一条
            UserhomeFund userhomeFund=new UserhomeFund();
            userhomeFund.setUserhomeId(userhomeOrder.getUserhomeId());
            userhomeFund.setFundId(userhomeOrder.getFundId());
            userhomeFund.setOrderNum(userhomeOrder.getOrderNum());
            userhomeFund.setPayNum(tradeSn);
            userhomeFund.setCanRedeemNum(userhomeOrder.getNum());
            userhomeFund.setNum(userhomeOrder.getNum());
            userhomeFund.setStatus(1);
            userhomeFund.setProfitDay(new Date());
            userhomeFundMapper.insert(userhomeFund);
            //已购基金余额变动
            Userhome userhome = userhomeMapper.selectById(userhomeOrder.getUserhomeId());
            userhome.setFundMoney(userhome.getFundMoney()+userhomeOrder.getAmount());
            userhome.setIsBuy(1);
            userhomeMapper.updateById(userhome);

        }

        //已过期变成异常
        else if(userhomeOrder.getStatus()==2)
        {
            userhomeOrder.setStatus(3);
        }
        userhomeOrder.setPayNum(tradeSn);
        this.baseMapper.updateById(userhomeOrder);
        return Result.OK("成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> handleSupplement(String outTradeNo)
    {
        UserhomeOrder userhomeOrder = this.baseMapper.getByOrderNumLock(outTradeNo);
        if(userhomeOrder.getStatus()!=3)
        {
            return Result.error("只要异常订单才能补");
        }
        userhomeOrder.setStatus(1);
        this.baseMapper.updateById(userhomeOrder);
        Fund fund = fundMapper.getByIdLock(userhomeOrder.getFundId());
        if (fund == null) {
            return Result.error("基金已下架!");
        }
        if (fund.getStockNum() < userhomeOrder.getNum()) {
            return Result.error("基金份额不足!");
        }
        if (!fund.getStatus().equals(1)) {
            return Result.error("基金已下架!");
        }
        //库存变化
        fund.setStockNum(fund.getStockNum() - userhomeOrder.getNum());
        fund.setBuyNum(fund.getBuyNum() + userhomeOrder.getNum());
        fundMapper.updateById(fund);
        //新增用户基金
        //用户基金列表新增目前购买一次新增一条
        UserhomeFund userhomeFund=new UserhomeFund();
        userhomeFund.setUserhomeId(userhomeOrder.getUserhomeId());
        userhomeFund.setFundId(userhomeOrder.getFundId());
        userhomeFund.setOrderNum(userhomeOrder.getOrderNum());
        userhomeFund.setPayNum(userhomeOrder.getPayNum());
        userhomeFund.setCanRedeemNum(userhomeOrder.getNum());
        userhomeFund.setProfitDay(new Date());
        userhomeFund.setNum(userhomeOrder.getNum());
        userhomeFund.setStatus(1);
        userhomeFundMapper.insert(userhomeFund);
        Userhome userhome = userhomeMapper.selectById(userhomeOrder.getUserhomeId());
        userhome.setFundMoney(userhome.getFundMoney()+userhomeOrder.getAmount());
        userhomeMapper.updateById(userhome);
        return Result.OK("补单成功！");
    }


    //*****个人钱包提取相关逻辑***//
    //钱包提取
    @Override
   /* @Transactional(rollbackFor = Exception.class)*/
    public Result<?> withraw(Userhome userhome, WithdrawOrder withdrawOrder)
    {
        if (withdrawOrder.getAmount() <= 0) {
            return Result.error("金额不能为0");
        }
        if(userhome.getMoney()<withdrawOrder.getAmount())
        {
            return Result.error("余额不足");
        }
        YcUserhomeBank ycUserhomeBank=ycUserhomeBankMapper.selectById(withdrawOrder.getUserhomeBankId());
        if(ycUserhomeBank.getStatus()!=1)
        {
            return Result.error("银行卡不允许");
        }
        if(!ycUserhomeBank.getUserhomeId().equals(userhome.getId()))
        {
            return Result.error("银行卡不合规");
        }
        if(userhome.getIsAuthentication()==0)
        {
            return Result.error("账户没用实名认证");
        }
        MallConfiguration mallConfiguration= mallConfigurationMapper.getByMkey("withraw_rate");
        Double rate=Double.valueOf(mallConfiguration.getMvalue());
        userhome.setMoney(userhome.getMoney()-withdrawOrder.getAmount());
        userhomeMapper.updateById(userhome);
        UserhomeOrder userhomeOrder = new UserhomeOrder();
        userhomeOrder.setCreateBy("自行申请");
        userhomeOrder.setCreateTime(new Date());
        userhomeOrder.setUpdateBy("自行申请");
        userhomeOrder.setUpdateTime(new Date());
        userhomeOrder.setApplyAmount(withdrawOrder.getAmount());
        userhomeOrder.setAmount(withdrawOrder.getAmount()*(1-rate));
        userhomeOrder.setUserhomeBankId(withdrawOrder.getUserhomeBankId());
        userhomeOrder.setPayType(0);
        userhomeOrder.setType(3);
        userhomeOrder.setUserhomeId(userhome.getId());
        String orderNum = YinShengUtil.OrderNum("JT");
        userhomeOrder.setOrderNum(orderNum);
        userhomeOrder.setStatus(0);
        this.baseMapper.insert(userhomeOrder);
        //流水记录
        UserhomeWalletLog userhomeWalletLog=new UserhomeWalletLog();
        userhomeWalletLog.setUserhomeId(userhome.getId());
        userhomeWalletLog.setAmount(withdrawOrder.getAmount());
        userhomeWalletLog.setType(1);
        userhomeWalletLog.setSmoney(userhome.getMoney());
        userhomeWalletLog.setRelateOrderNum(userhomeOrder.getOrderNum());
        userhomeWalletLogMapper.insert(userhomeWalletLog);
        return Result.ok("success");
    }

    //钱包提取审核
    @Override
  //  @Transactional(rollbackFor = Exception.class)
    public Result<?> examine(UserhomeOrder userhomeOrder)
    {
        lock.lock();
        try {
        UserhomeOrder temp=this.baseMapper.selectById(userhomeOrder.getId());
        if(temp.getStatus()!=0)
        {
            return Result.error("该订单状态无法审核");
        }
        //拒绝
        if(userhomeOrder.getStatus()==6)
        {

            temp.setStatus(6);
            temp.setExamineTime(new Date());
            temp.setExamineContent(userhomeOrder.getExamineContent());
            temp.setExamineUrl(userhomeOrder.getExamineUrl());
            this.baseMapper.updateById(temp);
            //增加余额
            Userhome  userhome= userhomeMapper.selectById(temp.getUserhomeId());
            userhome.setMoney(userhome.getMoney()+temp.getApplyAmount());
            userhomeMapper.updateById(userhome);

            //流水记录
            UserhomeWalletLog userhomeWalletLog=new UserhomeWalletLog();
            userhomeWalletLog.setUserhomeId(userhome.getId());
            userhomeWalletLog.setAmount(temp.getApplyAmount());
            userhomeWalletLog.setType(3);
            userhomeWalletLog.setSmoney(userhome.getMoney());
            userhomeWalletLog.setRelateOrderNum(temp.getOrderNum());
            userhomeWalletLogMapper.insert(userhomeWalletLog);
        }

        //同意
        if(userhomeOrder.getStatus()==5)
        {
            Userhome  userhome= userhomeMapper.selectById(temp.getUserhomeId());
            if(oConvertUtils.isEmpty(userhome.getYingShengMerchantNo()))
            {
                return Result.error("账号异常");
            }
            YcUserhomeBank  ycUserhomeBank= ycUserhomeBankMapper.selectById(temp.getUserhomeBankId());
            YcYingshengBank ycYingshengBank=ycYingshengBankService.getById(ycUserhomeBank.getYingshengbankid());
            temp.setStatus(5);
            temp.setExamineTime(new Date());
            this.baseMapper.updateById(temp);
            //打款
            YcYingshengTransfer ycYingshengTransfer=new YcYingshengTransfer();
            String requestNo = temp.getOrderNum();
            ycYingshengTransfer.setOrdernum(requestNo);
            ycYingshengTransfer.setMerchantno(userhome.getYingShengMerchantNo());
            ycYingshengTransfer.setMoney(BigDecimal.valueOf(temp.getAmount()));
            ycYingshengTransfer.setStatus(0);
            ycYingshengTransfer.setType(1);
            ycYingshengTransfer.setCreatetime(new Date());
            ycYingshengTransfer.setRelationordernum(temp.getOrderNum());
            ycYingshengTransfer.setLinkid(ycYingshengBank.getLinkid());
            ycYingshengTransferService.save(ycYingshengTransfer);
            Result<JSONObject> result = YinShengUtil.transferInner(userhome.getYingShengMerchantNo(),String.valueOf(temp.getAmount()), requestNo, "B2C");
            if(result.isSuccess())
            {
                ycYingshengTransfer.setPaycode(result.getResult().getString("tradeSn"));
                ycYingshengTransfer.setStatus(2);
                ycYingshengTransferService.updateById(ycYingshengTransfer);
            } else {
                ycYingshengTransfer.setStatus(3);
                ycYingshengTransfer.setMessage(result.getResult().getString("subMsg"));
                ycYingshengTransferService.updateById(ycYingshengTransfer);
                temp.setStatus(4);
                this.baseMapper.updateById(temp);
            }
        }
        } finally {
            lock.unlock();
        }

        return Result.ok("success");
    }

    //钱包
    @Override
    public Result<JSONObject> callBackFa(String outTradeNo,String tradeSn)
    {
        //转账
        LambdaQueryWrapper<YcYingshengTransfer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(YcYingshengTransfer::getOrdernum,outTradeNo);
        YcYingshengTransfer  ycYingshengTransfer=ycYingshengTransferService.getOne(queryWrapper);
        //只有待支付才能更改成已支付
        if (ycYingshengTransfer.getStatus()!= 2) {
            return Result.error("状态不允许");
        }
        ycYingshengTransfer.setStatus(1);
        ycYingshengTransfer.setPaycode(tradeSn);
        ycYingshengTransferService.updateById(ycYingshengTransfer);
        LambdaQueryWrapper<UserhomeOrder> orderQueryWrapper=new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(UserhomeOrder::getOrderNum,ycYingshengTransfer.getRelationordernum());
        UserhomeOrder temp=this.baseMapper.selectOne(orderQueryWrapper);
        temp.setStatus(1);
        this.baseMapper.updateById(temp);
        return Result.ok("success");
    }
    //*****个人钱包提取相关逻辑***//

    //*****基金赎回相关逻辑***//
    //基金赎回
    public Result<?> withrawFund(Userhome userhome, WithdrawFund withdrawFund,String orderNum)
    {
        lock.lock();
        try {
            UserhomeFund   userhomeFund=userhomeFundMapper.selectById(withdrawFund.getUserhomeFundId());
        if(userhomeFund.getStatus()==0)
        {
            return Result.error("不能赎回");
        }
        if(userhomeFund.getStatus()==3)
        {
                return Result.error("已完全赎回");
        }
        if(userhomeFund.getCanRedeemNum()<withdrawFund.getAmount())
        {
                return Result.error("份额不足够");
        }
        if (withdrawFund.getAmount() <= 0) {
                return Result.error("金额不能为0");
        }
        if(userhome.getIsAuthentication()==0)
        {
                return Result.error("账户没用实名认证");
        }
        YcUserhomeBank ycUserhomeBank=ycUserhomeBankMapper.selectById(withdrawFund.getUserhomeBankId());
        if(ycUserhomeBank.getStatus()!=1)
        {
            return Result.error("银行卡不允许");
        }
        if(!ycUserhomeBank.getUserhomeId().equals(userhome.getId()))
        {
                return Result.error("银行卡不合规");
        }
        userhome.setFundMoney(userhome.getFundMoney()-withdrawFund.getAmount());
        userhomeMapper.updateById(userhome);
        userhomeFund.setStatus(4);
        userhomeFund.setRedeemNum(userhomeFund.getRedeemNum()+withdrawFund.getAmount());
        userhomeFund.setCanRedeemNum(userhomeFund.getCanRedeemNum()-withdrawFund.getAmount());
        userhomeFundMapper.updateById(userhomeFund);
        UserhomeOrder userhomeOrder = new UserhomeOrder();
        userhomeOrder.setCreateBy("自行申请");
        userhomeOrder.setCreateTime(new Date());
        userhomeOrder.setUpdateBy("自行申请");
        userhomeOrder.setUpdateTime(new Date());
        double rate=this.redeemRate(userhomeFund);
        userhomeOrder.setAmount(withdrawFund.getAmount()*(1-rate));
        userhomeOrder.setApplyAmount(withdrawFund.getAmount());
        userhomeOrder.setUserhomeBankId(withdrawFund.getUserhomeBankId());
        userhomeOrder.setPayType(0);
        String firstTwoChars = orderNum.substring(0, 2);
        if(firstTwoChars.equals("FT"))
        {
            userhomeOrder.setType(2);

        }
        else
        {
            userhomeOrder.setType(5);

        }
        userhomeOrder.setRelationId(withdrawFund.getUserhomeFundId());
        userhomeOrder.setUserhomeId(userhome.getId());
        userhomeOrder.setFundId(userhomeFund.getFundId());
        userhomeOrder.setRelationOrderNum(userhomeFund.getOrderNum());
        userhomeOrder.setOrderNum(orderNum);
        userhomeOrder.setStatus(0);
        this.baseMapper.insert(userhomeOrder);

    } finally {
        lock.unlock();
    }
        return Result.ok("success");
    }


    //基金赎回审核
    @Override
    //  @Transactional(rollbackFor = Exception.class)
    public Result<?> examineFund(UserhomeOrder userhomeOrder)
    {
        lock.lock();
        try {
            UserhomeOrder temp=this.baseMapper.selectById(userhomeOrder.getId());
            if(temp.getStatus()!=0)
            {
                return Result.error("该订单状态无法审核");
            }
            //拒绝
            if(userhomeOrder.getStatus()==6)
            {
                temp.setStatus(6);
                temp.setExamineTime(new Date());
                temp.setExamineContent(userhomeOrder.getExamineContent());
                temp.setExamineUrl(userhomeOrder.getExamineUrl());
                this.baseMapper.updateById(temp);
                //增加已购基金金额
                Userhome  userhome= userhomeMapper.selectById(temp.getUserhomeId());
                userhome.setFundMoney(userhome.getFundMoney()+temp.getApplyAmount());
                userhomeMapper.updateById(userhome);
                //用户基金返回
                UserhomeFund   userhomeFund=userhomeFundMapper.selectById(temp.getRelationId());
                userhomeFund.setRedeemNum(userhomeFund.getRedeemNum()-temp.getApplyAmount());
                userhomeFund.setCanRedeemNum(userhomeFund.getCanRedeemNum()+temp.getApplyAmount());
                if(userhomeFund.getRedeemNum()!=0)
                {
                    userhomeFund.setStatus(2);
                }
                else
                {
                    userhomeFund.setStatus(1);
                }
                userhomeFundMapper.updateById(userhomeFund);
            }

            //同意
            if(userhomeOrder.getStatus()==5)
            {
                Userhome  userhome= userhomeMapper.selectById(temp.getUserhomeId());
                if(oConvertUtils.isEmpty(userhome.getYingShengMerchantNo()))
                {
                    return Result.error("账号异常");
                }
                YcUserhomeBank  ycUserhomeBank= ycUserhomeBankMapper.selectById(temp.getUserhomeBankId());
                YcYingshengBank ycYingshengBank=ycYingshengBankService.getById(ycUserhomeBank.getYingshengbankid());
                temp.setStatus(5);
                temp.setExamineTime(new Date());
                this.baseMapper.updateById(temp);
                //打款
                YcYingshengTransfer ycYingshengTransfer=new YcYingshengTransfer();
                String requestNo = temp.getOrderNum();
                ycYingshengTransfer.setOrdernum(requestNo);
                ycYingshengTransfer.setMerchantno(userhome.getYingShengMerchantNo());
                ycYingshengTransfer.setMoney(BigDecimal.valueOf(temp.getAmount()));
                ycYingshengTransfer.setStatus(0);
                ycYingshengTransfer.setType(1);
                ycYingshengTransfer.setCreatetime(new Date());
                ycYingshengTransfer.setRelationordernum(temp.getOrderNum());
                ycYingshengTransfer.setLinkid(ycYingshengBank.getLinkid());
                ycYingshengTransferService.save(ycYingshengTransfer);
                Result<JSONObject> result = YinShengUtil.transferInner(userhome.getYingShengMerchantNo(),String.valueOf(temp.getAmount()), requestNo, "B2C");
                if(result.isSuccess())
                {
                    ycYingshengTransfer.setPaycode(result.getResult().getString("tradeSn"));
                    ycYingshengTransfer.setStatus(2);
                    ycYingshengTransferService.updateById(ycYingshengTransfer);
                } else {
                    ycYingshengTransfer.setStatus(3);
                    ycYingshengTransfer.setMessage(result.getResult().getString("subMsg"));
                    ycYingshengTransferService.updateById(ycYingshengTransfer);
                    temp.setStatus(4);
                    this.baseMapper.updateById(temp);
                }
            }
        } finally {
            lock.unlock();
        }

        return Result.ok("success");
    }


    //基金
    @Override
    public Result<JSONObject> callBackFa2(String outTradeNo,String tradeSn)
    {
        //转账
        LambdaQueryWrapper<YcYingshengTransfer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(YcYingshengTransfer::getOrdernum,outTradeNo);
        YcYingshengTransfer  ycYingshengTransfer=ycYingshengTransferService.getOne(queryWrapper);
        //只有待支付才能更改成已支付
        if (ycYingshengTransfer.getStatus()!= 2) {
            return Result.error("状态不允许");
        }
        ycYingshengTransfer.setStatus(1);
        ycYingshengTransfer.setPaycode(tradeSn);
        ycYingshengTransferService.updateById(ycYingshengTransfer);
        LambdaQueryWrapper<UserhomeOrder> orderQueryWrapper=new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(UserhomeOrder::getOrderNum,ycYingshengTransfer.getRelationordernum());
        UserhomeOrder temp=this.baseMapper.selectOne(orderQueryWrapper);
        temp.setStatus(1);
        this.baseMapper.updateById(temp);
        //基金状态
        UserhomeFund   userhomeFund=userhomeFundMapper.selectById(temp.getRelationId());
        if(userhomeFund.getCanRedeemNum()==0)
        {
            userhomeFund.setStatus(3);
        }
        else
        {
            userhomeFund.setStatus(2);
        }
        userhomeFundMapper.updateById(userhomeFund);
        //减去用户基金
        //已购基金余额变动
        Userhome userhome=userhomeMapper.selectById(temp.getUserhomeId());
        userhome.setFundMoney(userhome.getFundMoney()-temp.getAmount());
        userhomeMapper.updateById(userhome);
        return Result.ok("success");
    }
    //*****基金赎回相关逻辑***//


    //*****基金钱包提取相关逻辑***//
    //钱包提取
    @Override
    /* @Transactional(rollbackFor = Exception.class)*/
    public Result<?> withrawFundMoney(Userhome userhome, WithdrawOrder withdrawOrder)
    {
        if(userhome.getFMoney()<withdrawOrder.getAmount())
        {
            return Result.error("余额不足");
        }
        if(userhome.getIsAuthentication()==0)
        {
            return Result.error("账户没用实名认证");
        }
        if (withdrawOrder.getAmount() <= 0) {
            return Result.error("金额不能为0");
        }
        YcUserhomeBank ycUserhomeBank=ycUserhomeBankMapper.selectById(withdrawOrder.getUserhomeBankId());
        if(ycUserhomeBank.getStatus()!=1)
        {
            return Result.error("银行卡不允许");
        }
        if(!ycUserhomeBank.getUserhomeId().equals(userhome.getId()))
        {
            return Result.error("银行卡不合规");
        }
        MallConfiguration mallConfiguration= mallConfigurationMapper.getByMkey("withraw_fund_rate");
        Double rate=Double.valueOf(mallConfiguration.getMvalue());
        userhome.setFMoney(userhome.getFMoney()-withdrawOrder.getAmount());
        userhomeMapper.updateById(userhome);
        UserhomeOrder userhomeOrder = new UserhomeOrder();
        userhomeOrder.setCreateBy("自行申请");
        userhomeOrder.setCreateTime(new Date());
        userhomeOrder.setUpdateBy("自行申请");
        userhomeOrder.setUpdateTime(new Date());
        userhomeOrder.setApplyAmount(withdrawOrder.getAmount());
        userhomeOrder.setAmount(withdrawOrder.getAmount()*(1-rate));
        userhomeOrder.setUserhomeBankId(withdrawOrder.getUserhomeBankId());
        userhomeOrder.setPayType(0);
        userhomeOrder.setType(4);
        userhomeOrder.setUserhomeId(userhome.getId());
        String orderNum = YinShengUtil.OrderNum("MQ");
        userhomeOrder.setOrderNum(orderNum);
        userhomeOrder.setStatus(0);
        this.baseMapper.insert(userhomeOrder);
        //流水记录
        UserhomeWalletFundLog userhomeWalletFundLog=new UserhomeWalletFundLog();
        userhomeWalletFundLog.setUserhomeId(userhome.getId());
        userhomeWalletFundLog.setAmount(withdrawOrder.getAmount());
        userhomeWalletFundLog.setType(1);
        userhomeWalletFundLog.setSmoney(userhome.getFMoney());
        userhomeWalletFundLog.setRelateOrderNum(userhomeOrder.getOrderNum());
        userhomeWalletFundLogMapper.insert(userhomeWalletFundLog);
        return Result.ok("success");
    }

    //钱包提取审核
    @Override
    //  @Transactional(rollbackFor = Exception.class)
    public Result<?> examineFundMoney(UserhomeOrder userhomeOrder)
    {
        lock.lock();
        try {
            UserhomeOrder temp=this.baseMapper.selectById(userhomeOrder.getId());
            if(temp.getStatus()!=0)
            {
                return Result.error("该订单状态无法审核");
            }
            //拒绝
            if(userhomeOrder.getStatus()==6)
            {
                Userhome  userhome= userhomeMapper.selectById(temp.getUserhomeId());
                if(oConvertUtils.isEmpty(userhome.getYingShengMerchantNo()))
                {
                    return Result.error("账号异常");
                }

                temp.setStatus(6);
                temp.setExamineTime(new Date());
                temp.setExamineContent(userhomeOrder.getExamineContent());
                temp.setExamineUrl(userhomeOrder.getExamineUrl());
                this.baseMapper.updateById(temp);
                //增加余额
                userhome.setFMoney(userhome.getFMoney()+temp.getApplyAmount());
                userhomeMapper.updateById(userhome);

                //流水记录
                UserhomeWalletFundLog userhomeWalletFundLog=new UserhomeWalletFundLog();
                userhomeWalletFundLog.setUserhomeId(userhome.getId());
                userhomeWalletFundLog.setAmount(temp.getApplyAmount());
                userhomeWalletFundLog.setType(3);
                userhomeWalletFundLog.setSmoney(userhome.getFMoney());
                userhomeWalletFundLog.setRelateOrderNum(temp.getOrderNum());
                userhomeWalletFundLogMapper.insert(userhomeWalletFundLog);
            }

            //同意
            if(userhomeOrder.getStatus()==5)
            {
                YcUserhomeBank  ycUserhomeBank= ycUserhomeBankMapper.selectById(temp.getUserhomeBankId());
                YcYingshengBank ycYingshengBank=ycYingshengBankService.getById(ycUserhomeBank.getYingshengbankid());
                temp.setStatus(5);
                temp.setExamineTime(new Date());
                this.baseMapper.updateById(temp);
                //打款
                Userhome  userhome= userhomeMapper.selectById(temp.getUserhomeId());
                YcYingshengTransfer ycYingshengTransfer=new YcYingshengTransfer();
                String requestNo = temp.getOrderNum();
                ycYingshengTransfer.setOrdernum(requestNo);
                ycYingshengTransfer.setMerchantno(userhome.getYingShengMerchantNo());
                ycYingshengTransfer.setMoney(BigDecimal.valueOf(temp.getAmount()));
                ycYingshengTransfer.setStatus(0);
                ycYingshengTransfer.setType(1);
                ycYingshengTransfer.setCreatetime(new Date());
                ycYingshengTransfer.setRelationordernum(temp.getOrderNum());
                ycYingshengTransfer.setLinkid(ycYingshengBank.getLinkid());
                ycYingshengTransferService.save(ycYingshengTransfer);
                Result<JSONObject> result = YinShengUtil.transferInner(userhome.getYingShengMerchantNo(),String.valueOf(temp.getAmount()), requestNo, "B2C");
                if(result.isSuccess())
                {
                    ycYingshengTransfer.setPaycode(result.getResult().getString("tradeSn"));
                    ycYingshengTransfer.setStatus(2);
                    ycYingshengTransferService.updateById(ycYingshengTransfer);
                } else {
                    ycYingshengTransfer.setStatus(3);
                    ycYingshengTransfer.setMessage(result.getResult().getString("subMsg"));
                    ycYingshengTransferService.updateById(ycYingshengTransfer);
                    temp.setStatus(4);
                    this.baseMapper.updateById(temp);
                }
            }
        } finally {
            lock.unlock();
        }

        return Result.ok("success");
    }
    //*****基金钱包提取相关逻辑***//

    //公用逻辑
    @Override
    public Result<JSONObject> callBacktransferInner(String outTradeNo,String tradeSn,String prefix) {
        try {
            System.out.println("休眠前: " + System.currentTimeMillis() / 1000);
            // 休眠5秒
            Thread.sleep(10000);
            //sb上游异步到账还不一定到账
            LambdaQueryWrapper<YcYingshengTransfer> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(YcYingshengTransfer::getOrdernum,outTradeNo);
            YcYingshengTransfer  ycYingshengTransfer=ycYingshengTransferService.getOne(queryWrapper);
            if(ycYingshengTransfer.getStatus()!=2)
            {
                return Result.error("状态异常");
            }
            System.out.println("休眠后: " + System.currentTimeMillis() / 1000);
            ycYingshengTransfer.setStatus(1);
            ycYingshengTransfer.setPaycode(tradeSn);
            ycYingshengTransferService.updateById(ycYingshengTransfer);
            LambdaQueryWrapper<YcYingshengUserwallt> queryWrapper2=new LambdaQueryWrapper<>();
            queryWrapper2.eq(YcYingshengUserwallt::getMerchantno,ycYingshengTransfer.getMerchantno());
            //更新钱包金额
            YcYingshengUserwallt  ycYingshengUserwallt=ycYingshengUserwalltService.getOne(queryWrapper2);
            ycYingshengUserwallt.setMoney(ycYingshengUserwallt.getMoney().add(ycYingshengTransfer.getMoney()));
            ycYingshengUserwalltService.updateById(ycYingshengUserwallt);
            //金额细节日志
            YcYingshengTransferLog ycYingshengTransferLogInsert=new YcYingshengTransferLog();
            ycYingshengTransferLogInsert.setOrdernum(outTradeNo);
            ycYingshengTransferLogInsert.setMerchantno(ycYingshengTransfer.getMerchantno());
            ycYingshengTransferLogInsert.setMoney(ycYingshengTransfer.getMoney());
            ycYingshengTransferLogInsert.setType(1);
            ycYingshengTransferLogInsert.setCreatetime(new Date());
            ycYingshengTransferLogInsert.setSmoney(ycYingshengUserwallt.getMoney());
            ycYingshengTransferLogService.save(ycYingshengTransferLogInsert);

            //立刻提现到银行卡
            String requestNo = YinShengUtil.OrderNum(prefix);
            BigDecimal amount = ycYingshengTransfer.getMoney();
            String payeeMerchantNo = ycYingshengTransfer.getMerchantno();
            String linkId = ycYingshengTransfer.getLinkid();

            //从账号到个人银行卡提款记录
            YcYingshengTransfer ycYingshengTransferToBank=new YcYingshengTransfer();
            ycYingshengTransferToBank.setOrdernum(requestNo);
            ycYingshengTransferToBank.setMerchantno(payeeMerchantNo);
            ycYingshengTransferToBank.setStatus(0);
            ycYingshengTransferToBank.setType(-1);
            ycYingshengTransferToBank.setLinkid(linkId);
            ycYingshengTransferToBank.setCreatetime(new Date());
            ycYingshengTransferToBank.setMoney(amount);
            ycYingshengTransferToBank.setRelationordernum(ycYingshengTransfer.getRelationordernum());
            ycYingshengTransferService.save(ycYingshengTransferToBank);

            Result<JSONObject> result = YinShengUtil.withdraw(requestNo, payeeMerchantNo, String.valueOf(amount.setScale(2, RoundingMode.HALF_UP)), linkId);
            if(result.isSuccess())
            {
                ycYingshengTransferToBank.setStatus(2);
                ycYingshengTransferToBank.setPaycode(result.getResult().getString("tradeSn"));
                ycYingshengTransferService.updateById(ycYingshengTransferToBank);
                //取钱先扣避免重复取钱
                ycYingshengUserwallt.setMoney(ycYingshengUserwallt.getMoney().subtract(amount));
                LambdaQueryWrapper<YcYingshengBank> bankQueryWrapper=new LambdaQueryWrapper<>();
                bankQueryWrapper.eq(YcYingshengBank::getLinkid,linkId);
                YcYingshengBank bank= ycYingshengBankService.getOne(bankQueryWrapper);
                bank.setWithrawMoney(bank.getWithrawMoney().add(amount));
                ycYingshengBankService.updateById(bank);
                //金额细节日志
                YcYingshengTransferLog ycYingshengTransferLogInsert2=new YcYingshengTransferLog();
                ycYingshengTransferLogInsert2.setOrdernum(requestNo);
                ycYingshengTransferLogInsert2.setMerchantno(ycYingshengTransfer.getMerchantno());
                ycYingshengTransferLogInsert2.setMoney(amount);
                ycYingshengTransferLogInsert2.setType(-1);
                ycYingshengTransferLogInsert2.setCreatetime(new Date());
                ycYingshengTransferLogInsert2.setSmoney(ycYingshengUserwallt.getMoney());
                ycYingshengTransferLogService.save(ycYingshengTransferLogInsert2);
            } else {
                ycYingshengTransfer.setStatus(3);
                ycYingshengTransfer.setMessage(result.getResult().getString("subMsg"));
                ycYingshengTransferService.updateById(ycYingshengTransfer);
                LambdaQueryWrapper<UserhomeOrder> orderQueryWrapper=new LambdaQueryWrapper<>();
                orderQueryWrapper.eq(UserhomeOrder::getOrderNum,ycYingshengTransfer.getRelationordernum());
                UserhomeOrder temp=this.baseMapper.selectOne(orderQueryWrapper);
                temp.setStatus(4);
                this.baseMapper.updateById(temp);
            }

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        return Result.ok("success");
    }

    //计算基金赎回手续费
    private double redeemRate(UserhomeFund userhomeFund)
    {
        //天数设置
        MallConfiguration mallConfiguration= mallConfigurationMapper.getByMkey("redeem_fund_time");
        Integer month=Integer.valueOf(mallConfiguration.getMvalue());
        MallConfiguration emallConfiguration= mallConfigurationMapper.getByMkey("redeem_fund_time_end");
        Integer emonth=Integer.valueOf(emallConfiguration.getMvalue());
        //不足月手续费
        MallConfiguration mallConfiguration2= mallConfigurationMapper.getByMkey("redeem_rate_nosufficient");
        Double redeemRateNosufficient=Double.valueOf(mallConfiguration2.getMvalue());
        //足月手续费
        MallConfiguration mallConfiguration3= mallConfigurationMapper.getByMkey("redeem_rate_sufficient");
        Double redeemRateSufficient=Double.valueOf(mallConfiguration3.getMvalue());
        Date addDate= FundDate.addMonths(userhomeFund.getCreateTime(),month);
        Date eDate= FundDate.addMonths(userhomeFund.getCreateTime(),emonth);
        Date nowDate=new Date();
        if (nowDate.compareTo(eDate) > 0) {
            return 0;
        }
        else if (nowDate.compareTo(addDate) > 0) {
           return redeemRateSufficient;
        } else {
            return redeemRateNosufficient;
        }

    }
}
